package com.lucas.Service;

import com.lucas.Handler.UserServerHandler;
import com.lucas.annation.ZookeeperServer;
import com.lucas.service.UserService;
import com.lucsa.jsonUtils.jsonUtil;
import com.lucsa.pojo.RpcRequest;
import com.lucsa.utils.RpcDecoder;
import com.lucsa.utils.RpcEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    /**
     * 服务器端提供rpc具体实现服务.
     * @param msg
     * @return
     */
    @Override
    public String sayHello(Object msg) {
        String result = "服务器端说:我从客户端接收到的信息:"+msg.toString();
        System.out.println(result);
        return "success";

    }


    @ZookeeperServer
    public void startServer(final UserServerHandler handler,Integer port) throws InterruptedException {

            //1.构建chanel
            NioEventLoopGroup bossGroup = new NioEventLoopGroup();
            NioEventLoopGroup workerGroup = new NioEventLoopGroup();

            //2.初始化服务端
            ServerBootstrap bootstrap = new ServerBootstrap();

            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            // 初始化监听器
                            ChannelPipeline pipeline = ch.pipeline();
//                            pipeline.addLast(new StringEncoder());
//                            pipeline.addLast(new StringDecoder());
                            pipeline.addLast(new RpcDecoder(RpcRequest.class,new jsonUtil()));
//                            pipeline.addFirst(new RpcDecoder(RpcRequest.class,new jsonUtil()));
                            pipeline.addLast(new RpcEncoder(RpcRequest.class,new jsonUtil()));

                            pipeline.addLast(handler);
                        }
                    });
            //绑定端口
            bootstrap.bind("127.0.0.1", port).sync();


    }
}
